/**
 * Created by chentao on 2016/2/27.
 */
var Socket;


if (!Socket) {
    Socket = {

    }
}

/**
 * 建立连接方法
 * @param options 心跳配置参数 {ip:"127.0.0.1",port:1234,open:function(),close:function(),message:function()}
 * @returns {Socket}
 */
Socket.connection = function (options) {
    isConnect = false;
    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }
    if (window.WebSocket) {
        client = window.WebSocket;
        client = new WebSocket("ws://"+options.ip+":"+options.port+"/ws");
        client.onmessage = function (event) {
            var data = JSON.parse(event.data);
            var action = data.action;
            if(action=='hart'){
                Socket.send({
                    action:'hart'
                });
                return false;
            }
            if(options.message!=undefined){
                options.message(event);
            }
        };
        client.onopen = function (event) {
            isConnect = true;
            if(options.open!=undefined) {
                options.open(event);
            }
        };
        client.onclose = function (event) {
            isConnect = false;
            if(options.close!=undefined){
                options.close(event);
            }
        };
    } else {
        alert("你的浏览器不支持 WebSocket！");
    }
    return this;
}

/**
 * 发送数据给客户端
 * @param msg  发送数据信息 {action:'login',msg:'123456'}
 * @returns {Socket}
 */
Socket.send = function (msg) {
    if (!isConnect&&!msg) {
        return;
    }
    if (client.readyState == WebSocket.OPEN) {
        var msg = {action:msg.action,msg:msg.msg};
        client.send(JSON.stringify(msg));
    } else {
        alert("连接没有开启.");
    }
    return this;
}
